import React, { Component } from "react";
import MainLayout from "@component/mainLayout/mainLayout";
import Button from "@component/button/index";
import { connect } from "react-redux";
import { InputItem, Toast, Modal } from "antd-mobile";
import "./index.scss";
import verCode from "@component/verCode/index";
import Icon from "@component/icon";
import BankItem from "./bankItem.js";
import {
	addNewBank,
	setSupportedBankList,
	getSelectedBankList,
	getSupportedBankList,
	checkUserBankInfo,
	checkBonus
} from "@redux/Action/bank/bank";
import { InterfaceG } from "@config/Config";
import BackModal from "@component/backModal/index";
import yhTools from "@tools/yh";
import iconXj from "@images/icon-xj1.png";
import { getAppPlatformsDatas } from "@redux/Action/nativeDatas/nativeDatas";
const BankIcon = require("@images/icon/helpTip1.png");
const nameAuthBanner = require("@images/img_home/name_auth_banner.png");

const submitCardRegexp = value => value.replace(/\s*/g, "");
const checkPhoneReg = value => /^1[3456789]\d{9}$/.test(value);
const checkBankReg = value => /^\d{13,19}$/.test(value);
const checkIdCard = value => /(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value);
const agreementPageMap = {
	1: "/agreementoflianyintong"
};
const year = new Date().getFullYear();
const month = new Date().getMonth() + 1;
const day = new Date().getDate();

const height = window.innerHeight;

/**
 * 小辉付添加银行卡
 */
@verCode()
@connect(
	state => ({
		bonusStr: state.bankReducer.bonusStr,
		supportedBankList: state.bankReducer.supportedBankList || [],
		applyNo: state.getAppPlatformsDatas.applyNo,
		lnid: state.getAppPlatformsDatas.lnid,
		ocrInfo: state.livenessReducer,
		longitude: state.getAppPlatformsDatas.longitude,
		latitude: state.getAppPlatformsDatas.latitude,
		mobile: state.getAppPlatformsDatas.mobile
	}),
	dispatch => ({
		checkBonus: (val1, val2) => dispatch(checkBonus(val1, val2)),
		addNewBank: value => dispatch(addNewBank(value)),
		setSupportedBankList: value => dispatch(setSupportedBankList(value)),
		getSelectedBankList: value => dispatch(getSelectedBankList(value)),
		getSupportedBankList: (value, fun) =>
			dispatch(getSupportedBankList(value, fun)),
		checkUserBankInfo: (value, fun) => dispatch(checkUserBankInfo(value, fun)),
		_getAppPlatformsDatas: value => dispatch(getAppPlatformsDatas(value))
	})
)
class xhfAddBank extends Component {
	constructor(props) {
		super(props);
		this.state = {
			overflow: "",
			idCard: "",
			isVisible: false,
			accountNo: "",
			verifyCode: "",
			channelCode: "YHB",
			userBankPhone: "",
			messageSerialNumber: "",
			verifier: "",
			from: "",
			isBackModalVisible: false,
			hasSendCode: false,
			canSubmit: true,
			headerBanner: "",
			spaceID: "",
			showBtn: true //是否显示底部按钮
		};
	}
	/**页面激活时复原，处理网络出错时回来不能点击 */
	componentDidRecover = () => {
		this.setState({ canSubmit: true });
	};
	componentWillUnmount() {
		if (window.YHAuthorize) {
			window.YHAuthorize.View.removeEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
	}
	keyboardEvent = obj => {
		const id = document.activeElement.getAttribute("id");
		if (id !== "fix-cursor") {
			let winHeight = document.documentElement.clientHeight;
			if (document.getElementById(`keybordb_${this.state.spaceID}`)) {
				document.getElementById(`keybordb_${this.state.spaceID}`).style.height =
					(winHeight * obj.heightper) / 2 + 74 + "px";
			}
		}
		if (id === "js-fix-bug") {
			document.activeElement.scrollIntoView();
		}
	};
	componentDidMount = () => {
		window.addEventListener("resize", () => {
			if (window.innerHeight !== height) {
				this.setState({
					showBtn: false
				});
			} else {
				this.setState({
					showBtn: true
				});
			}
		});
		this.initData();
	};
	initData = () => {
		this.getBannerList();
		// this.isHasLocation();
		// 宝付贷版本用的是YHB 换卡是ll连连, 连连是120s倒计时，华通是60s
		if (window.YHAuthorize) {
			window.YHAuthorize.View.addEventListener(
				"KeyboardEvent",
				this.keyboardEvent,
				false
			);
		}
		let _tempRandom = Math.round(Math.random() * 1000000);
		this.setState({
			spaceID: _tempRandom
		});
	};
	//去设置允许打开地理位置
	openLoction() {
		yhTools.settingPrivacy();
	}

	/**获取图片配置banner */
	getBannerList() {
		const params = {
			url: InterfaceG.getChannelBannerList,
			params: {
				pageType: "xhf_auth_image",
				productNo: "601"
			},
			_alertShow: false
		};
		yhTools.request(params).then(res => {
			const { code, data = {} } = res;
			if (code == "0") {
				const from = yhTools.getUrlParam("from");
				const fromBankList = from === "bankList";
				this.setState(
					{
						headerBanner:
							data["1"] && data["1"].length > 0 ? data["1"]["0"]["imgUrl"] : "",
						from,
						channelCode: "ll"
					},
					() => {
						const { checkUserBankInfo, getSupportedBankList } = this.props;
						const { channelCode } = this.state;
						if (fromBankList) {
							// TODO 优化，支付换卡和开户绑卡银行卡列表不一样
							checkUserBankInfo({ channelCode }, () => {
								this.props.checkBonus("60201");
							});
						} else {
							getSupportedBankList({ channelCode }, () => {
								this.props.checkBonus("60201");
							});
						}
					}
				);
			}
		});
	}
	//选择图片
	chooseImage() {
		//打开原生获取图片
		let imgPicker = {
			type: "3", //相机和相册
			imageName: this.props.mobile + "_card_" + ".png",
			imageSize: 100 * 1024 + "", // 100kb,自定义
			thumbnailSize: 100 * 1024 + "" // 100kb,自定义
		};

		yhTools.chooseImage(imgPicker).then(
			resp => {
				this.getOcrBank(resp.data.path);
			},
			() => {}
		);
	}

	//获取ocr银行卡
	getOcrBank(path) {
		const imageData = {
			name: "bankImg.jpeg",
			path: path,
			params: {}
		};
		const objs = {
			url: InterfaceG.orcBank,
			imageArray: [imageData]
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				this.setState({
					bankInfo: res.data,
					accountNo: res.data.cardNumber
						.replace(/\s/g, "")
						.replace(/(\w{4})(?=\w)/g, "$1 ")
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	}

	toggleVisible = isVisible => {
		this.setState({
			isVisible
		});
	};
	getMsgCode = () => {
		this.sendMsgCode();
	};
	sendMsgCode = () => {
		const { accountNo, userBankPhone, idCard, userName } = this.state;
		const { sendCode, isClick, setCountDown } = this.props.verCode;
		if (!userName) {
			Toast.info("请输入姓名", 2);
			return false;
		}
		if (!accountNo) {
			Toast.info("请输入银行卡号", 2);
			return false;
		}
		if (!checkBankReg(submitCardRegexp(accountNo))) {
			Toast.info("请输入正确的银行卡号", 2);
			return false;
		}
		if (!idCard) {
			Toast.info("请输入身份证", 2);
			return false;
		}
		if (!checkIdCard(submitCardRegexp(idCard))) {
			Toast.info("身份证格式不正确", 2);
			return false;
		}
		if (!userBankPhone) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(submitCardRegexp(userBankPhone))) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!isClick) return;
		setCountDown(120); //连连验证码时间
		let objs = {
			url: InterfaceG.sendBindCardVerifyCode,
			params: {
				mobilePhone: submitCardRegexp(userBankPhone),
				userName: submitCardRegexp(userName),
				accountNo: submitCardRegexp(accountNo),
				cardId: submitCardRegexp(idCard),
				scene: "04" //"01", "还款绑卡","02", "借款绑卡","03", "银行卡管理绑卡","04", "实名认证绑卡","05", "授信申请绑卡"
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 100);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				sendCode();
				const { orderNo, status } = res.data;
				this.setState({
					orderNo,
					status,
					overflow: "scroll",
					hasSendCode: true
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	};

	xhfAddBank = () => {
		const {
			accountNo,
			verifyCode,
			userBankPhone,
			idCard,
			userName,
			orderNo
		} = this.state;
		if (
			this.checkCanSubmit(
				accountNo,
				userBankPhone,
				verifyCode,
				idCard,
				userName
			)
		) {
			if (!this.state.canSubmit) return;
			this.setState({
				canSubmit: false
			});
			let objs = {
				url: InterfaceG.loanBindCard,
				params: {
					userName: submitCardRegexp(userName),
					cardId: submitCardRegexp(idCard),
					accountNo: submitCardRegexp(accountNo),
					verifyCode: submitCardRegexp(verifyCode),
					userBankPhone: submitCardRegexp(userBankPhone),
					channelCode: "ll",
					scene: "04", //"01", "还款绑卡","02", "借款绑卡","03", "银行卡管理绑卡","04", "实名认证绑卡","05", "授信申请绑卡"
					orderNo
				},
				_alertShow: false
			};
			Toast.loading("加载中...", 100);
			yhTools.request(objs).then(async res => {
				Toast.hide();
				this.setState({ canSubmit: true });
				if (res.code === "0") {
					Toast.success("实名认证成功", 3);
					setTimeout(() => {
						this.props.history.push("/xhqbIndex");
					}, 3000);
				} else {
					Toast.info(res.message, 2);
				}
			});
		}
	};
	InputOnChange = (key, value) => {
		this.setState({
			[key]: value
		});
	};
	checkCanSubmit = (cardNo, phoneNum, verifyCode, idCard, userName) => {
		if (!userName) {
			Toast.info("请输入姓名", 2);
			return false;
		}
		if (!cardNo) {
			Toast.info("请输入银行卡号", 2);
			return false;
		}
		if (!checkBankReg(submitCardRegexp(cardNo))) {
			Toast.info("请输入正确的银行卡号", 2);
			return false;
		}
		if (!idCard) {
			Toast.info("请输入身份证", 2);
			return false;
		}
		if (!checkIdCard(submitCardRegexp(idCard))) {
			Toast.info("身份证格式不正确", 2);
			return false;
		}
		if (!phoneNum) {
			Toast.info("请填写手机号", 2);
			return false;
		}
		if (!checkPhoneReg(submitCardRegexp(phoneNum))) {
			Toast.info("手机号格式不正确", 2);
			return false;
		}
		if (!this.state.hasSendCode) {
			Toast.info("请获取验证码", 2);
			return false;
		}
		if (!verifyCode.length) {
			Toast.info("请输入验证码");
			return false;
		}
		if (verifyCode.length !== 6) {
			Toast.info("验证码输入错误");
			return false;
		}
		return true;
	};
	/** 检查是否设置支付密码 */
	async checkSetPassword() {
		let objs = {
			url: InterfaceG.checkSetPassword,
			params: {},
			_alertShow: false
		};

		Toast.loading("加载中...", 100);
		let res = await yhTools.request(objs);
		Toast.hide();
		if (res.code === "0") {
			return true;
		} else if (res.code === "70010") {
			return false;
		} else {
			Toast.info(res.message, 2);
			return null;
		}
	}
	addNewBankFn = async () => {
		// 防止重复提交，待优化
		const {
			channelCode,
			accountNo,
			userBankPhone,
			verifyCode,
			messageSerialNumber,
			verifier,
			idCard,
			userName
		} = this.state;
		if (
			this.checkCanSubmit(
				accountNo,
				userBankPhone,
				verifyCode,
				idCard,
				userName
			)
		) {
			if (!this.state.canSubmit) return;
			this.setState({
				canSubmit: false
			});
			let objs = {
				url: InterfaceG.addNewCard,
				params: {
					channelCode,
					accountNo,
					userBankPhone,
					verifyCode,
					messageSerialNumber,
					verifier
				},
				_alertShow: false
			};
			Toast.loading("加载中...", 100);
			yhTools.request(objs).then(res => {
				this.setState({ canSubmit: true });
				Toast.hide();
				if (res.code === "0") {
					this.props.getSelectedBankList({ channelCode });
					setTimeout(() => {
						this.props.history.goBack();
					}, 0);
				} else {
					Toast.info(res.message, 2);
				}
			});
		}
	};
	saveBank = () => {
		this.xhfAddBank();
	};

	//查看协议
	openContract = type => {
		const { userName, idNo } = this.props.ocrInfo;
		const commonParams = {
			personName: userName,
			idCardCode: idNo,
			year,
			month,
			day
		};
		this.props.history.push({
			pathname: agreementPageMap[type],
			params: commonParams
		});
	};
	onModalClick = booleanValue => {
		this.setState({
			isBackModalVisible: false
		});
		!booleanValue && this.props.history.push("/xhfHomeNoCredit");
	};
	showModal = () => {
		this.setState({
			isVisible: false,
			isBackModalVisible: true
		});
	};
	updateBank = () => {
		this.chooseImage();
	};
	render() {
		const {
			isVisible,
			isBackModalVisible,
			userBankPhone,
			from,
			accountNo,
			hasSendCode,
			idCard,
			userName,
			showBtn,
			overflow
		} = this.state;
		const { supportedBankList, lnid } = this.props;
		const _pageParams = {
			header: {
				title: "实名认证"
			},
			componentDidRecover: () => {
				// 缓存
				this.initData();
			},
			isModal: from === "liveness",
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles
		};
		const { countDown, isClick } = this.props.verCode;
		return (
			<MainLayout pageParams={_pageParams} handleBack={this.showModal}>
				<BackModal
					product={lnid}
					isVisible={isBackModalVisible}
					onClick={this.onModalClick}
				/>

				<div style={{ overflow: overflow }} className="xhqb-add-bank-wrapper">
					<div className="add-bank-container">
						<img className="name_auth_banner" src={nameAuthBanner} alt="" />
						<InputItem
							className="my-input"
							defaultValue={userName}
							disabled={false}
							placeholder="请输入姓名"
							id="js-fix-bug"
							onChange={this.InputOnChange.bind(this, "userName")}
						>
							姓名
						</InputItem>
						{/* 23包括空格 */}
						<InputItem
							maxLength="23"
							className="my-input my-clear1"
							placeholder="请输入银行卡号"
							type="bankCard"
							id="js-fix-bug"
							clear
							value={accountNo}
							onChange={this.InputOnChange.bind(this, "accountNo")}
						>
							银行卡号
							<img
								src={iconXj}
								className="icon-xj"
								onClick={() => this.updateBank()}
							/>
							<img
								alt="guide"
								className="icon-help"
								src={BankIcon}
								onClick={() => this.toggleVisible(true)}
							/>
						</InputItem>
						<InputItem
							clear
							maxLength={18}
							type="text"
							id="js-fix-bug"
							placeholder="请输入身份证号码"
							defaultValue={idCard}
							className="my-input"
							onChange={this.InputOnChange.bind(this, "idCard")}
						>
							身份证号码
						</InputItem>
						<InputItem
							clear
							type="phone"
							id="js-fix-bug"
							placeholder="请填写预留手机号"
							defaultValue={userBankPhone}
							className="my-input"
							onChange={this.InputOnChange.bind(this, "userBankPhone")}
						>
							预留手机号
						</InputItem>
						<InputItem
							clear
							placeholder="请输入验证码"
							maxLength={6}
							minLength={6}
							id="js-fix-bug"
							pattern="[0-9]{6}"
							type="tel"
							className="my-input my-clear2"
							onChange={this.InputOnChange.bind(this, "verifyCode")}
						>
							验证码
							<span className="get-code" onClick={this.getMsgCode}>
								{/* {isClick ? "获取验证码" : countDown} */}

								{isClick
									? hasSendCode
										? "重新发送"
										: "获取验证码"
									: countDown}
							</span>
						</InputItem>
						<div className="tips">
							<Icon code="iconic_tip" />
							信息加密处理，仅用于银行验证
						</div>
					</div>
					{showBtn && (
						<div className="add-bank-button">
							<div className="agreement" onClick={() => this.openContract(1)}>
								<p>
									点击按钮，表示您已阅读并同意<i>《连连支付相关协议》</i>
								</p>
								<p>银行卡信息将用于账户实名认证</p>
							</div>
							<Button onClick={this.saveBank}>同意协议并认证</Button>
						</div>
					)}
				</div>

				<Modal
					visible={isVisible}
					transparent
					maskClosable={true}
					title="银行卡支持列表"
					closable={true}
					onClose={() => this.toggleVisible(false)}
					className="bank-list-modal"
				>
					<div style={{ height: 300, overflow: "scroll" }}>
						{supportedBankList.map(item => (
							<BankItem item={item} key={Math.random()} />
						))}
					</div>
				</Modal>
			</MainLayout>
		);
	}
}
export default xhfAddBank;
